﻿using AdminWeb.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using XW.Web.Framework;
using XW.Web.Framework.Jwt;
using Microsoft.Extensions.Options;
using XW.Core;
using XW.Data;
using Microsoft.IdentityModel.Tokens;
using XW.Utils;
using Microsoft.AspNetCore.Http.Extensions;
using AdminWeb.Areas.Sys.Models;
using SqlSugar;

namespace AdminWeb.Areas.Sys.Controllers
{
    /// <summary>
    ///  TODO  菜单管理控制器
    /// </summary>

    [Area("Sys")]
    [Authorize]
    public class MenuController : BaseController
    {
        private readonly SqlSugarRepository<SysMenu> _menuRep;
        private readonly ILogger<MenuController> _logger;
        public MenuController(ILogger<MenuController> logger,SqlSugarRepository<SysMenu> menuRep) { 
            this._menuRep = menuRep;
            this._logger = logger;
        }
        public IActionResult List()
        {
            return View();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> AllListAsync()
        {
            var pageModel = CommonHelper.GetPageModel<UserPageModel>("sort", "asc");
            RefAsync<int> count = 0;
            var query = _menuRep.AsQueryable();
            query.Where(d => d.IsDelete == false);
            // 关键字查询
            query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.Name.Contains(pageModel.Keyword)
                || u.permission.Contains(pageModel.Keyword)
                || u.Url.Contains(pageModel.Keyword) 
                || u.Remark.Contains(pageModel.Keyword));

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            // 排序
            var list = await query.ToListAsync();

            return GetSuccessResult(list);
        }


        /// <summary>
		/// 编辑
		/// </summary>
		/// <returns></returns>
		public IActionResult Edit(long id = 0)
        {
            SysMenu menu = null;
            if (id > 0)
            {
                menu = _menuRep.GetById(id);
                if (menu == null)
                {
                    return Content("<h1>菜单不存在！</h1>");
                }
            }
            else
            {
                menu = new SysMenu();
            }

            //ViewData["CurrentUser"] = user;
            return View(menu);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Save()
        {
            long id = CommonHelper.ToInt64(this.Request.Form["id"]);
            string Name = this.Request.Form["Name"]; // 菜单名
            string Icon = this.Request.Form["Icon"]; // 图标
            string Url = this.Request.Form["Url"];
            string permission = this.Request.Form["permission"];
            int IsShow = CommonHelper.ToInt(this.Request.Form["IsShow"]);
            long ParentId = CommonHelper.ToInt64(this.Request.Form["ParentId"]);
            string Remark = this.Request.Form["Remark"];
            int MenuType = CommonHelper.ToInt(this.Request.Form["MenuType"]);
            int Status = CommonHelper.ToInt(this.Request.Form["Status"]);
            string JsMethod = this.Request.Form["JsMethod"];
            int Sort = CommonHelper.ToInt( this.Request.Form["Sort"]);  // 排序



            if (Name.IsNullOrEmpty())
            {
                return GetErrorResult("菜单名不能为空");
            }

            if (id == 0)
            { 
                var menu = new SysMenu();
                menu.Name = Name;
                menu.Icon = Icon;
                menu.Url = Url;
                menu.permission = permission;
                menu.IsShow = IsShow;
                menu.ParentId = ParentId; 
                menu.Remark = Remark;
                menu.MenuType = MenuType;
                menu.Status = Status;
                menu.JsMethod = JsMethod; 
                menu.Sort = Sort;
                menu.IsDelete = false;
                _menuRep.Insert(menu);
            }
            else
            {
                // 检查是否循环
                if (CheckIsCircularMenu(id, ParentId))
                {
                    return GetErrorResult("父菜单设置错误，引发循环引用！");
                }
                _menuRep.AsUpdateable()
                    .SetColumns(u => u.Name == Name)
                    .SetColumns(u => u.Icon == Icon)
                    .SetColumns(u => u.Url == Url)
                    .SetColumns(u => u.permission == permission)
                    .SetColumns(u => u.IsShow == IsShow)
                    .SetColumns(u => u.ParentId == ParentId)
                    .SetColumns(u => u.Remark == Remark)
                    .SetColumns(u => u.MenuType == MenuType)
                    .SetColumns(u => u.Status == Status)
                    .SetColumns(u => u.JsMethod == JsMethod)
                    .SetColumns(u => u.Sort == Sort)
                   .setColumnsUpdateUserAndTime()
                   .Where(u => u.Id == id).ExecuteCommand();
            }

            return GetSuccessResult("保存成功！");

        } 

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Delete(long id = 0)
        {
            SysMenu menu = _menuRep.GetById(id);
            if (menu == null)
            {
                return GetErrorResult("菜单不存在");
            }
            var result = await _menuRep.DeleteByIdAsync(id);
            return GetSuccessResult("操作成功！");
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> BatDelete()
        {
            string ids = Request.Form["ids"];
            if (ids.IsNullOrEmpty())
            {
                return GetErrorResult("请选择需要删除的数据");
            }
            var idlist = ids.Split(',').Select(d => CommonHelper.ToInt64(d)).ToArray();
            var result = await _menuRep.DeleteAsync(d => idlist.Contains(d.Id));
            return GetSuccessResult("操作成功！");
        }


        private bool CheckIsCircularMenu(long id, long ParentId) {
            if (ParentId == 0 ) {
                return false;
            }
            if (id == ParentId)
            {
                return true;
            }
            var list = _menuRep.AsQueryable().Where(d => d.IsDelete == false).ToList();
            var menus = new List<long>();
            menus.Add(ParentId);
            menus.Add(0);
            while (true)
            {
                if (ParentId == 0)
                {
                    break;
                }
                var parent = list.Where(d => d.Id == ParentId).SingleOrDefault();
                if (parent == null)
                {
                    break;
                }
                else
                {
                    if (parent.Id == id)
                    {
                        return true;
                    }
                    menus.Add(parent.Id); 
                }
                ParentId = parent.ParentId; 
            }
            if (menus.IndexOf(id) > -1)
            {
                return true;
            }
            return false; 
        }
    }
}
